package com.sj.service.impl;

import com.sj.common.exception.CustomException;
import com.sj.entity.User;
import com.sj.security.SecurityUser;
import com.sj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-08-02
 * Time: 下午 15:24
 * Description: security UserDetail实现类
 * @author xiaoqi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new CustomException("用户名未找到");
        }
        return new SecurityUser(user.getId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getId()));
    }

    /**
     * 获取用户权限信息，角色 + 菜单 权限
     * @param id
     * @return
     */
    public Collection<? extends GrantedAuthority> getUserAuthority(Integer id) {
        String authority = userService.getUserAuthorityInfo(id);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}